﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using API;
using System.ServiceModel;
using GanoESB;
using Newtonsoft.Json;
using System.Reflection;
using System.ServiceModel.Channels;

namespace Service1
{
    public class Service1Impl : IService1
    {
        private IService2 CreateService<T>(ServiceItem item)
        {
            Type serviceType = typeof(T);
            var channelFactoryType = typeof(ChannelFactory<>);
            channelFactoryType = channelFactoryType.MakeGenericType(serviceType);

            ChannelFactory channelFactory = (ChannelFactory)Activator.CreateInstance(channelFactoryType);
            MethodInfo createchannel = channelFactory.GetType().GetMethod("CreateChannel", new Type[] { typeof(Binding), typeof(EndpointAddress) });

            return (IService2)createchannel.Invoke(channelFactory, new object[] { new NetNamedPipeBinding(), new EndpointAddress(item.ServiceUrl) });
        }

        #region IService1 成员

        public virtual string SayHello(string name)
        {
            if (name == "billy")
                throw new Exception("error test.");

            IServiceFinder callback = OperationContext.Current.GetCallbackChannel<IServiceFinder>();

            ServiceItem item = callback.FindServiceByType(typeof(IService2).FullName);

            IService2 srv = CreateService<IService2>(item);
            return srv.SayHello2(name);   
            //return "hi:" + name;
        }

        #endregion
    }
}
